package org.teachertools.web.actions;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.teachertools.common.ValidationUtils;
import org.teachertools.data.Competence;
import org.teachertools.data.Livret;
import org.teachertools.services.CompetenceService;
import org.teachertools.services.LivretService;
import org.teachertools.services.exception.ServiceException;
import org.teachertools.web.forms.LivretForm;
import org.teachertools.web.forms.LivretFormMapping;

public class LivretAction extends CommonDispatchAction {
    /**
     * @see org.apache.struts.actions.LookupDispatchAction#getKeyMethodMap()
     */
    @Override
    protected Map<String, String> getKeyMethodMap() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("button.init", "init");
        map.put("button.create", "create");
        map.put("button.update", "update");
        map.put("button.save", "save");
        map.put("button.delete", "delete");
        map.put("button.deleteCompetence", "deleteCompetence");
        return map;
    }

    public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        addLivretList(request);
        return mapping.findForward("successInit");
    }

    public ActionForward common(ActionMapping mapping, LivretForm livretForm, HttpServletRequest request, String forward)
            throws Exception {
        Long idCategorie = livretForm.getIdCategorie();
        if (idCategorie != null) {
            request.setAttribute("idCategorie", idCategorie);
        }
        addCategoryList(request);
        addMatiereList(request);
        addFilteredCompetenceList(livretForm, request);

        return mapping.findForward(forward);
    }

    public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        LivretForm livretForm = (LivretForm) form;
        Livret livret = LivretFormMapping.mappingFormToDTO(livretForm);
        LivretService livretService = getServiceLocator().getLivretService();
        livretService.save(livret);
        LivretFormMapping.mappingDTOToForm(livret, livretForm);

        return common(mapping, livretForm, request, "successCreate");
    }

    public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        LivretForm livretForm = (LivretForm) form;
        Long idCategorie = livretForm.getIdCategorie();
        Long idMatiere = livretForm.getIdMatiere();

        LivretService livretService = getServiceLocator().getLivretService();
        Livret livret = livretService.get(livretForm.getId());
        LivretFormMapping.mappingDTOToForm(livret, livretForm);
        livretForm.setIdCategorie(idCategorie);
        livretForm.setIdMatiere(idMatiere);

        addCategoryList(request);
        addMatiereList(request);
        addFilteredCompetenceList(livretForm, request);
        request.setAttribute("COMPETENCE_LIST", livret.getCompetences());

        return common(mapping, livretForm, request, "successUpdate");
    }

    public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        LivretForm livretForm = (LivretForm) form;
        LivretService livretService = this.getServiceLocator().getLivretService();
        Livret livret = livretService.get(livretForm.getId());

        CompetenceService competenceService = this.getServiceLocator().getCompetenceService();
        Set<Competence> competenceList = livret.getCompetences();
        Long[] ids = livretForm.getCompetenceIds();
        for (Long id : ids) {
            Competence comp = competenceService.get(id);
            competenceList.add(comp);
        }
        livretService.update(livret);

        addCategoryList(request);
        addMatiereList(request);
        addFilteredCompetenceList(livretForm, request);
        request.setAttribute("COMPETENCE_LIST", livret.getCompetences());

        return common(mapping, livretForm, request, "successSave");
    }

    public ActionForward deleteCompetence(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        LivretForm livretForm = (LivretForm) form;
        LivretService livretService = this.getServiceLocator().getLivretService();
        Livret livret = livretService.get(livretForm.getId());

        Long[] ids = livretForm.getCompetenceIds();
        for (Long id : ids) {
            Iterator<Competence> competenceIterator = livret.getCompetences().iterator();
            while (competenceIterator.hasNext()) {
                Competence comp = competenceIterator.next();
                if (comp.getId().equals(id)) {
                    competenceIterator.remove();
                }
            }
        }
        livretService.update(livret);

        Long idCategorie = livretForm.getIdCategorie();
        if (idCategorie != null) {
            request.setAttribute("idCategorie", idCategorie);
        }
        addCategoryList(request);
        Long idMatiere = livretForm.getIdMatiere();
        if (idMatiere != null) {
            request.setAttribute("idMatiere", idMatiere);
        }
        addMatiereList(request);
        addFilteredCompetenceList(livretForm, request);
        request.setAttribute("COMPETENCE_LIST", livret.getCompetences());

        return common(mapping, livretForm, request, "successSave");
    }

    public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        LivretForm livretForm = (LivretForm) form;

        LivretService livretService = this.getServiceLocator().getLivretService();
        Long id = livretForm.getId();
        livretService.deleteById(id);
        livretForm.reset();

        ActionMessages actionMessages = new ActionMessages();
        actionMessages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("success.do", getMessage(request,
                "libelle.lasuppression")));
        saveMessages(request, actionMessages);

        addLivretList(request);
        return mapping.findForward("successDelete");
    }

    private void addFilteredCompetenceList(LivretForm livretForm, HttpServletRequest request) throws ServiceException {
        Long idMatiere = livretForm.getIdMatiere();
        if (ValidationUtils.isNotEmpty(idMatiere)) {
            CompetenceService competenceService = getServiceLocator().getCompetenceService();
            List<Competence> liste = competenceService.getCompetenceNotUsedInLivret(livretForm.getId(), livretForm
                    .getIdMatiere());
            request.setAttribute("COMPETENCE", liste);
        }
    }
}
